package com.qxzn.module.home.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.lmc.SkillsDetailsActivity;
import com.lmc.adapter.HomeSelectPagerAdapter;
import com.lmc.entity.Skills;
import com.lmc.util.JsonManager;
import com.lmc.view.CardTransformer;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BannerBean;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.EventBusBean;
import com.qxzn.app.page.BaseFragment;
import com.qxzn.app.page.banner.BannerHelper;
import com.qxzn.app.page.model.HomeModel;
import com.qxzn.app.page.robot.RobotHelper;
import com.qxzn.app.page.util.GlideBannerImageLoader;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.Constant;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.agora.VideoChatCallActivity;
import com.qxzn.module.agora.VideoMonitoringActivity;
import com.qxzn.module.home.R;
import com.qxzn.module.home.R2;
import com.qxzn.module.home.activity.CareRemindActivity;
import com.qxzn.module.home.activity.NewsActivity;
import com.qxzn.module.home.activity.PictureShareActivity;
import com.qxzn.module.home.adapter.WidgetItemAdapter;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements OnLoadMoreListener, OnRefreshListener {
    @BindView(R2.id.tv_name)
    TextView robotName;
    @BindView(R2.id.widget_recycle_view)
    LRecyclerView skillsRecycleView;

    private List<Skills.SkillsBen> skillsBens = new ArrayList<>();

    private HomeModel homeModel;
    private ViewHolder headHolder;
    RobotHelper robotHelper;

    @Override
    protected int initLayout() {
        return R.layout.fragment_home;
    }

    @Override
    public void onEventBus(EventBusBean busBean) {
        super.onEventBus(busBean);
        if (busBean.getId() == Constant.EventBusId.SWITCH_DEVICE_ID) {
            updateRobot();
        }
    }

    private void updateRobot() {
        String name = SharePreferenceUtil.getDeviceName(getContext());
        robotName.setText(TextUtils.isEmpty(name) ? getText(R.string.no_robot_default_name) : name);
    }

    ViewPager viewPager;//精选技能的滚动列表
    HomeSelectPagerAdapter pagerAdapter;
    List<Skills> select_list = new ArrayList<>();

    @Override
    protected void initView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_head_home, (ViewGroup) getActivity().findViewById(android.R.id.content), false);
        headHolder = new ViewHolder(view);
        viewPager = view.findViewById(R.id.view_pager);

        pagerAdapter = new HomeSelectPagerAdapter(getContext(), select_list);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(2);//预加载2个
        viewPager.setPageMargin(-70);//设置viewpage之间的间距
        viewPager.setClipChildren(false);
        viewPager.setPageTransformer(true, new CardTransformer());
        viewPager.setCurrentItem(1);
        getSkill(1);

        LRecyclerViewAdapter widgetAdapter = new LRecyclerViewAdapter(new WidgetItemAdapter(getActivity(), skillsBens));
        widgetAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                // todo 点击技能
                SkillsDetailsActivity.start(getContext(), skillsBens.get(position).getId() + "");
            }
        });
        skillsRecycleView.setAdapter(widgetAdapter);
        skillsRecycleView.setOnLoadMoreListener(this);
        skillsRecycleView.setOnRefreshListener(this);
        widgetAdapter.addHeaderView(view);

        getSkillList();
    }

    /**
     * 获取全部技能列表
     */
    private void getSkillList() {
        JSONObject params = new JSONObject();
        HttpRequest.getService().getSkill(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.e("-----------", "获取全部技能列表：" + string);
                    Skills skills = JsonManager.parseJson(string, Skills.class);
                    skillsBens.clear();
                    skillsBens.addAll(skills.getData());
                    skillsRecycleView.getAdapter().notifyDataSetChanged();
                } catch (Exception e) {
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }

    /**
     * 获取精选技能列表
     */
    private void getSkill(final int type) {
        if (type > 3) {
            return;
        }
        JSONObject params = new JSONObject();
        params.put("type", String.valueOf(type));
        HttpRequest.getService().getSkill(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.e("-----------", "获取精选技能列表：" + string);
                    Skills skills = JsonManager.parseJson(string, Skills.class);
                    select_list.add(skills);
                    pagerAdapter.notifyDataSetChanged();
                    int i = type;
                    getSkill(++i);
                } catch (Exception e) {
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }


    @OnClick({R2.id.iv_add, R2.id.tv_name})
    public void onViewClicked(View view) {
        if (CommonUtil.isFastClick()) return;
        int i = view.getId();
        if (i == R.id.iv_add) {
            // 添加机器人
            robotHelper.startAddRobot();
        } else if (i == R.id.tv_name) {
            // 切换机器人
            if (TextUtils.isEmpty(SharePreferenceUtil.getDeviceId(getContext()))) {
                robotHelper.startAddRobot();
            } else {
                robotHelper.startSwitchRobot(robotName.getText().toString().trim(), 0);
            }
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        robotHelper = new RobotHelper(getActivity());
        homeModel = new HomeModel(getActivity());
        headHolder.banner.setImages(headHolder.imageList).setImageLoader(new GlideBannerImageLoader()).start();
        updateRobot();
        initBanner();
    }

    private void initBanner() {
        JSONObject params = new JSONObject();
        HttpRequest.getService().getSeriesHome(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean<List<BannerBean>>>() {
            @Override
            public void onResponse(Call<BaseBean<List<BannerBean>>> call, Response<BaseBean<List<BannerBean>>> response) {
                BaseBean<List<BannerBean>> body = response.body();
                if (body.getCode() == 200) {
                    List<BannerBean> bannerBeanList = body.getData();
                    List<String> images = new ArrayList<>();
                    for (BannerBean b : bannerBeanList) {
                        images.add(HttpRequest.BASE_URL + b.bg);
//                        Log.e("--------", "图片路径 :" + HttpRequest.BASE_URL + b.getBg());
                    }
                    if (images.size() > 0) {
                        updateBanner(images, bannerBeanList);
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseBean<List<BannerBean>>> call, Throwable t) {
                ToastUtil.showTextToast(getContext(), getString(R.string.network_error));
            }
        });
    }

    private void updateBanner(List<String> images, List<BannerBean> bannerBeanList) {
        headHolder.banner.setOnBannerListener(null);
        headHolder.bannerList.clear();
        headHolder.imageList.clear();
        headHolder.imageList.addAll(images);
        headHolder.banner.setImages(headHolder.imageList);
        if (bannerBeanList != null) {
            headHolder.bannerList.addAll(bannerBeanList);
            headHolder.banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    BannerBean bannerBean = headHolder.bannerList.get(position);
                    BannerHelper.jumping(getActivity(), bannerBean.type_param, null, bannerBean.name);
                }
            });
        }
        headHolder.banner.start();
    }

    @Override
    public void onDestroy() {
        homeModel.removeListener();
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        loadData(0);
    }

    @Override
    public void onLoadMore() {
        loadData(1);
    }

    // todo API上没有设计分布加载
    private void loadData(final int page) {
        skillsRecycleView.postDelayed(new Runnable() {
            @Override
            public void run() {
                skillsRecycleView.refreshComplete(0);
//                if (page == 0)
//                    widgetList.clear();
//                int i = 5;
//                while (i-- > 0)
//                    widgetList.add((int) (Math.random() * 3));
                skillsRecycleView.getAdapter().notifyDataSetChanged();
            }
        }, 1000);
    }

    static class ViewHolder {
        @BindView(R2.id.banner)
        Banner banner;
        private Context context;

        private List<BannerBean> bannerList = new ArrayList<>();
        List<String> imageList = new ArrayList<>();

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
            context = view.getContext();
        }

        @OnClick({R2.id.voice_calls, R2.id.video_calls, R2.id.video_monitoring, R2.id.message,
                R2.id.remind, R2.id.member, R2.id.photo, R2.id.news})
        public void onViewClicked(View view) {
            if (CommonUtil.isFastClick()) return;
            int i = view.getId();
            if (i == R.id.voice_calls) {
                // 语音通话
                // todo
            } else if (i == R.id.video_calls) {
                // 视频通话
                context.startActivity(new Intent(context, VideoChatCallActivity.class));
            } else if (i == R.id.video_monitoring) {
                // 视频监控
                context.startActivity(new Intent(context, VideoMonitoringActivity.class));
            } else if (i == R.id.message) {
                // 留言
                // todo
                context.startActivity(new Intent(context, CareRemindActivity.class));
            } else if (i == R.id.remind) {
                // 提醒
                context.startActivity(new Intent(context, CareRemindActivity.class));
            } else if (i == R.id.member) {
                // 家庭成员
                context.startActivity(new Intent().setComponent(new ComponentName(context.getApplicationContext(), "com.qxzn.module.mine.activity.FamilyMemberActivity")));
            } else if (i == R.id.photo) {
                // 相册
                context.startActivity(new Intent(context, PictureShareActivity.class));
            } else if (i == R.id.news) {
                // 消息中心
                context.startActivity(new Intent(context, NewsActivity.class));
            }
        }
    }
}
